package bancosys.tec.exception;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

import org.apache.commons.lang.StringUtils;

/**
 * Holder for many messages.
 * 
 * @author lundberg
 */
public class CompoundMessageHolder implements LocalizedMessageHolder {

    private final List<LocalizedMessageHolder> holders = new ArrayList<LocalizedMessageHolder>();

    private final String separator;

    /**
     * Constructor
     * 
     * @param separator separator
     */
    public CompoundMessageHolder(String separator) {
        this.separator = separator;
    }

    /**
     * Constructor
     */
    public CompoundMessageHolder() {
        this("\n");
    }

    /**
     * Adds another message to the holder
     * 
     * @param message message
     * @return self
     */
    public CompoundMessageHolder addMessage(LocalizedMessageHolder message) {
        this.holders.add(message);
        return this;
    }

    /**
     * Adds some messages to the holder
     * 
     * @param messages messages
     * @return self
     */
    public CompoundMessageHolder addMessages(Collection<? extends LocalizedMessageHolder> messages) {
        this.holders.addAll(messages);
        return this;
    }

    /**
     * {@inheritDoc}
     */
    public String getMessage() {
        List<String> messages = new ArrayList<String>(this.holders.size());
        for (LocalizedMessageHolder holder : this.holders) {
            messages.add(holder.getMessage());
        }
        return StringUtils.join(messages, this.separator);
    }

    /**
     * {@inheritDoc}
     */
    public String getMessage(Locale locale) {
        List<String> messages = new ArrayList<String>(this.holders.size());
        for (LocalizedMessageHolder holder : this.holders) {
            messages.add(holder.getMessage(locale));
        }
        return StringUtils.join(messages, this.separator);
    }

    /**
     * @return list of holders
     */
    public List<LocalizedMessageHolder> getMessages() {
        return Collections.unmodifiableList(this.holders);
    }

}
